package com.imooc.apigateway.filter;

import com.imooc.apigateway.RedisConstant.RedisConstant;
import com.imooc.apigateway.utils.CookieUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @Author snail
 * @Description: 权限拦截（区分买家和卖家）
 * @create: 2020-04-20 16:22
 * @Param $
 * @return $
 * @Version 1.0
 **/
@Component
public class AuthFilter extends ZuulFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        /*
        * /order/create 只能买家访问
        * /order/finish 只能卖家访问
        * /product/list 都可访问
        * */
        if("http://127.0.0.1:8086/order/order/create".equals(request.getRequestURL().toString())){
        //if("/order/order/create".equals(request.getRequestURL())){
            Cookie cookie= CookieUtil.get(request,"openid");
            if(cookie==null || StringUtils.isEmpty(cookie.getValue())){
                requestContext.setSendZuulResponse(false);
                requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            }
        }
        if("http://127.0.0.1:8086/order/order/finish".equals(request.getRequestURL().toString())){
            Cookie cookie= CookieUtil.get(request,"token");
            if(cookie==null || StringUtils.isEmpty(cookie.getValue() ) ||
                    StringUtils.isEmpty(stringRedisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_TRMPLATE,cookie.getValue())))){
                requestContext.setSendZuulResponse(false);
                requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            }
        }
        return null;
    }
}
